package com.fjb.controller.cart;


import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.collections4.map.HashedMap;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fjb.common.entity.HttpCode;
import com.fjb.common.entity.JsonResult;
import com.fjb.common.entity.TotalResult;
import com.fjb.common.enums.DataSource;
import com.fjb.common.enums.product.AttrType;
import com.fjb.common.enums.product.ProductStatus;
import com.fjb.common.enums.user.AddressStatus;
import com.fjb.common.global.GlobalConfig;
import com.fjb.controller.base.BaseController;
import com.fjb.dto.LoginUserInfo;
import com.fjb.pojo.cart.ShoppingCart;
import com.fjb.pojo.cart.vo.ShoppingCartVo;
import com.fjb.pojo.product.ProductAttribute;
import com.fjb.pojo.product.ProductAttributeSku;
import com.fjb.pojo.product.ProductInfo;
import com.fjb.pojo.product.vo.ProductFilesVo;
import com.fjb.pojo.product.vo.ProductSpecAttributeVo;
import com.fjb.pojo.product.vo.ProductSpecificationVo;
import com.fjb.pojo.user.SysUserAddress;
import com.fjb.service.cart.ShoppingCartService;
import com.fjb.service.product.ProductInfoService;
import com.fjb.service.user.SysUserAddressService;

/**
 * <p>
 * 购物车 前端控制器
 * </p>
 *
 * @author hemiao
 * @since 2019-12-22
 */
@Controller
@RequestMapping("/shoppingCart")
public class ShoppingCartController extends BaseController{
	
	@Autowired
	private ShoppingCartService shoppingCartService;
	@Autowired
	private StringRedisTemplate redisTemplate;
	@Autowired
	private SysUserAddressService sysUserAddressService;
	@Autowired
	private ProductInfoService productInfoService;
	
	/**
	 * @Description:获得购物车列表
	 * @param request
	 * @return
	 * JsonResult<List<ShoppingCartVo>>
	 * @exception:
	 * @author: hemiao
	 * @time:2020年1月30日 下午8:40:00
	 */
	@RequestMapping(value="/selectList")
	@ResponseBody
	public JsonResult<List<ShoppingCartVo>> selectList(HttpServletRequest request){
		LoginUserInfo userInfo = getBaseWxTokenId(request);
		Integer userId = userInfo.getUserId();
		ShoppingCart cart = new ShoppingCart();
		cart.setUserId(userId);	
		List<ShoppingCartVo> list = shoppingCartService.selectCartList(cart);
		return new JsonResult<List<ShoppingCartVo>>(list, HttpCode.SUCCESS);
	}
	
	/**
	 * @Description:获得购物车数量
	 * @param request
	 * @return
	 * JsonResult<Integer>
	 * @exception:
	 * @author: hemiao
	 * @time:2020年2月4日 下午9:50:03
	 */
	@RequestMapping(value="/getCartCount")
	@ResponseBody
	public JsonResult<Integer> getCartCount(HttpServletRequest request){
		LoginUserInfo userInfo2 = getBaseWxTokenIdTwo(request);
		if(userInfo2!=null) {		
			if(userInfo2!=null) {	
				Integer userId = userInfo2.getUserId();
				QueryWrapper<ShoppingCart> queryWrapper = new QueryWrapper<ShoppingCart>();
				queryWrapper.eq("user_id", userId);
				int count = shoppingCartService.count(queryWrapper);
				return new JsonResult<Integer>(count, HttpCode.SUCCESS);
			}
		}	
		return new JsonResult<Integer>(0, HttpCode.SUCCESS);
	}
	
	/**
	 * @Description:添加购物车
	 * @param request
	 * @param productId	产品id
	 * @param number	 数量
	 * @return
	 * JsonResult<List<ShoppingCart>>
	 * @exception:
	 * @author: hemiao
	 * @time:2020年2月4日 下午8:41:54
	 */
	@RequestMapping(value="/addCart")
	@ResponseBody
	public JsonResult<List<ShoppingCart>> addCart(HttpServletRequest request,Integer productId,
			Integer number,Integer attrSkuId,BigDecimal skuPrice){
		HttpCode httpCode = HttpCode.PARAM_VERIFICATION;
		if(productId==null) {	
			httpCode.setMsg("产品id不能为空");
			return new JsonResult<List<ShoppingCart>>(null, httpCode);
		}
		if(number==null) {
			httpCode.setMsg("购买数量不能为空");
			return new JsonResult<List<ShoppingCart>>(null, httpCode);
		}
		if(skuPrice==null) {	
			httpCode.setMsg("价格不能为空");
			return new JsonResult<List<ShoppingCart>>(null, httpCode);
		}
		if(attrSkuId==null) {
			httpCode.setMsg("请选择完整规格");
			return new JsonResult<List<ShoppingCart>>(null, httpCode);
		}	
		String skuFileUrl = request.getParameter("skuFileUrl");
		if(StringUtils.isBlank(skuFileUrl)) {
			httpCode.setMsg("商品图片不能为空");
			return new JsonResult<List<ShoppingCart>>(null, httpCode);
		}
		String checkedSkuListStr = request.getParameter("checkedSkuListStr");
		if(StringUtils.isBlank(checkedSkuListStr)) {
			httpCode.setMsg("sku规格不能为空");
			return new JsonResult<List<ShoppingCart>>(null, httpCode);
		}
		
		ProductInfo productInfo = productInfoService.getById(productId);
		if(productInfo==null) {
			httpCode.setMsg("产品信息没找到");
			return new JsonResult<List<ShoppingCart>>(null, httpCode);
		}
		// 卖家id
		Integer sellerUserId = productInfo.getMainUserId();
		// 产品名称
		String productName = productInfo.getProductName();
		// 分类id
		Integer categoryId = productInfo.getCategoryId();
		// 品牌id
		Integer brandId = productInfo.getBrandId();
		// 产品单位
		String productUnit = productInfo.getProductUnit();
			
		LoginUserInfo userInfo = getBaseWxTokenId(request);
		Integer userId = userInfo.getUserId();
		Integer mainUserId = userInfo.getMainUserId();
		ShoppingCart cart = new ShoppingCart();
		cart.setMainUserId(mainUserId);
		cart.setUserId(userId);
		cart.setSellerUserId(sellerUserId);
		cart.setProductId(productId);
		cart.setCreateTime(LocalDateTime.now());
		cart.setCreateUserId(userId);
		cart.setSkuPrice(skuPrice);
		cart.setAttrSkuId(attrSkuId);
		cart.setAttrSkuJson(checkedSkuListStr);
		cart.setSkuCount(number);
		cart.setSkuFileUrl(skuFileUrl);	
		cart.setCartChecked(1);
		cart.setProductName(productName);
		cart.setProductUnit(productUnit);
		cart.setCategoryId(categoryId);
		cart.setBrandId(brandId);	
		cart.setDataSource(DataSource.WX_APPLET.getCode());
		shoppingCartService.save(cart);	
		return new JsonResult<List<ShoppingCart>>(null, HttpCode.SUCCESS);
	}
	
	/**
	 * @Description:购物车选中 和 未选中
	 * @param request
	 * @param cartId
	 * @param cartChecked
	 * @return
	 * JsonResult<Boolean>
	 * @exception:
	 * @author: hemiao
	 * @time:2020年2月6日 下午4:39:58
	 */
	@RequestMapping(value="/cartChecked")
	@ResponseBody
	public JsonResult<Boolean> cartChecked(HttpServletRequest request,Integer cartId,Integer cartChecked){
		HttpCode httpCode = HttpCode.PARAM_VERIFICATION;
		if(cartId==null) {	
			httpCode.setMsg("购物车id不能为空");
			return new JsonResult<Boolean>(null, httpCode);
		}
		if(cartChecked==null) {	
			return new JsonResult<Boolean>(null, httpCode);
		}
		if(cartChecked.equals(1)||cartChecked.equals(2)) {
			LoginUserInfo userInfo = getBaseWxTokenId(request);
			Integer userId = userInfo.getUserId();
			
			ShoppingCart cart = new ShoppingCart();
			cart.setId(cartId);
			cart.setCartChecked(cartChecked);
			
			QueryWrapper<ShoppingCart> updateWrapper = new QueryWrapper<ShoppingCart>();
			updateWrapper.eq("user_id", userId);
			updateWrapper.eq("id", cartId);
			boolean b = shoppingCartService.update(cart, updateWrapper);
			if(b==false) {
				httpCode.setMsg("操作失败");
				return new JsonResult<Boolean>(b, httpCode);
			}
			return new JsonResult<Boolean>(b, HttpCode.SUCCESS);
		}else {
			return new JsonResult<Boolean>(null, httpCode);
		}
	}
	
	/**
	 * @Description:修改购物车
	 * @param request
	 * @param cartId
	 * @param number
	 * @return
	 * JsonResult<Boolean>
	 * @exception:
	 * @author: hemiao
	 * @time:2020年2月6日 下午7:15:41
	 */
	@RequestMapping(value="/updateCart")
	@ResponseBody
	public JsonResult<Boolean> updateCart(HttpServletRequest request,Integer cartId ,Integer number ){
		HttpCode httpCode = HttpCode.PARAM_VERIFICATION;
		if(cartId==null) {	
			httpCode.setMsg("购物车id不能为空");
			return new JsonResult<Boolean>(null, httpCode);
		}
		if(number==null) {	
			return new JsonResult<Boolean>(null, httpCode);
		}
		LoginUserInfo userInfo = getBaseWxTokenId(request);
		Integer userId = userInfo.getUserId();
		
		ShoppingCart cart = new ShoppingCart();
		cart.setId(cartId);
		cart.setSkuCount(number);
		QueryWrapper<ShoppingCart> updateWrapper = new QueryWrapper<ShoppingCart>();
		updateWrapper.eq("user_id", userId);
		updateWrapper.eq("id", cartId);
		boolean b = shoppingCartService.update(cart, updateWrapper);
		if(b==false) {
			httpCode.setMsg("操作失败");
			return new JsonResult<Boolean>(b, httpCode);
		}
		return new JsonResult<Boolean>(b, HttpCode.SUCCESS);
	}
	
	/**
	 * @Description:删除购物车
	 * @param request
	 * @return
	 * JsonResult<Boolean>
	 * @exception:
	 * @author: hemiao
	 * @time:2020年2月6日 下午7:19:33
	 */
	@RequestMapping(value="/deleteCart")
	@ResponseBody
	public JsonResult<Boolean> deleteCart(HttpServletRequest request){
		HttpCode httpCode = HttpCode.PARAM_VERIFICATION;
		String cartIds = request.getParameter("cartIds");
		if(StringUtils.isBlank(cartIds)) {	
			return new JsonResult<Boolean>(null, httpCode);
		}
		List<Integer> cartIdList = new ArrayList<Integer>();
		String[] cartIdsAry = cartIds.split(",");
		for (int i = 0; i < cartIdsAry.length; i++) {
			String cartId = cartIdsAry[i];
			cartIdList.add(Integer.valueOf(cartId));
		}	
		LoginUserInfo userInfo = getBaseWxTokenId(request);
		Integer userId = userInfo.getUserId();
		QueryWrapper<ShoppingCart> removeWrapper = new QueryWrapper<ShoppingCart>();
		removeWrapper.eq("user_id", userId);
		removeWrapper.in("id", cartIdList);		
		boolean b = shoppingCartService.remove(removeWrapper);
		if(b==false) {
			httpCode.setMsg("操作失败");
			return new JsonResult<Boolean>(b, httpCode);
		}
		return new JsonResult<Boolean>(b, HttpCode.SUCCESS);
	}
	
	// checkout
	@RequestMapping(value="/selectCheckout")
	@ResponseBody
	public JsonResult<Map<String, Object>> selectCheckout(HttpServletRequest request,Integer addressId){
		HashedMap<String, Object> resultMap = new HashedMap<String, Object>();
		LoginUserInfo userInfo = getBaseWxTokenId(request);
		Integer userId = userInfo.getUserId();
		ShoppingCart cart = new ShoppingCart();
		cart.setUserId(userId);	
		// 查询选中的商品	
		cart.setCartChecked(1);
		List<ShoppingCartVo> checkedProductList = shoppingCartService.selectCartList(cart);
		resultMap.put("checkedProductList", checkedProductList);
			
		// 默认的收货地址  	checkedAddress
		QueryWrapper<SysUserAddress> queryWrapper = new QueryWrapper<SysUserAddress>();
		if(addressId!=null) {
			queryWrapper.eq("id", addressId);
		}else {
			queryWrapper.eq("default_status", 1);
		}	
		queryWrapper.eq("user_id", userId);
		queryWrapper.eq("address_status", AddressStatus.STATUS_1.getCode());
		SysUserAddress checkedAddress = sysUserAddressService.getOne(queryWrapper);
		resultMap.put("checkedAddress", checkedAddress);
		return new JsonResult<Map<String,Object>>(resultMap, HttpCode.SUCCESS);
	}
}
